<template>
  <div class="page-miH page-bgBack">
    <PageHeader @back="$router.go(-1)" subTitle="返回">用工单位设置</PageHeader>
    <a-spin :spinning="loading">
      <div style="padding: 24px">
        <a-tabs type="card" @change="callback">
          <a-tab-pane key="1" tab="小程序设置">
            <a-layout style="padding: 0; background: #fff">
              <a-layout-sider width="200" style="background: #fff">
                <a-menu mode="inline" :default-selected-keys="[0]">
                  <a-menu-item v-for="(item, index) in subjectList" :key="index" @click="menuChange(item)">
                    <span>{{ item.name }}</span>
                  </a-menu-item>
                </a-menu>
              </a-layout-sider>
              <!-- <a-divider type="vertical" style="height:auto" /> -->

              <a-layout-content :style="{ padding: '0 18px', minHeight: '280px' }">
                <div style="width: 100%; font-size: 18px; font-weight: 600; display: flex; justify-content: space-between">
                  <div>{{ appName }}</div>
                  <div v-if="appItem">
                    <a-switch v-model="appItem.isHide" default-checked @change="hideChange(appItem)">
                      <a-icon slot="checkedChildren" type="check" />
                      <a-icon slot="unCheckedChildren" type="close" />
                    </a-switch>
                  </div>
                </div>
                <a-divider style="margin-top: 12px" />
                <div class="itemBox" v-if="appList && appList.length > 0" :key="keyDate">
                  <template v-for="(item, index) in appList">
                    <div v-if="!(isJF && ['工资条', '考勤打卡', '社保公积金'].includes(item.name))" class="item" :key="index">
                      <div style="display: flex">
                        <div>
                          <img style="width: 42px; height: 42px" :src="item.icon[0]" alt />
                        </div>
                        <div style="margin-left: 12px">
                          <div style="font-weight: 500; color: #3c3d43; font-size: 14px; margin-bottom: 8px">
                            {{ item.name }}
                            <span class="Set" style="cursor: pointer" @click="openSet(item)">设置</span>
                          </div>
                          <div style="color: #a6a8b4; font-size: 12px">{{ item.desc ? item.desc : "---" }}</div>
                        </div>
                      </div>
                      <div>
                        <a-switch default-checked v-model="item.isHide" @change="hideChange(item)">
                          <a-icon slot="checkedChildren" type="check" />
                          <a-icon slot="unCheckedChildren" type="close" />
                        </a-switch>
                      </div>
                    </div>
                  </template>
                  <a-modal :title="setName + '设置'" :visible="visible" @ok="handleOk" @cancel="handleCancel">
                    <div style="height: 350px; overflow: scroll">
                      <div class="itemBox" v-if="setList && setList.length > 0">
                        <div class="item2" v-for="(item, index) in setList" :key="index">
                          <div style="display: flex">
                            <div>
                              <img style="width: 42px; height: 42px" :src="item.icon[0]" alt />
                            </div>
                            <div style="margin-left: 12px">
                              <div style="font-weight: 500; color: #3c3d43; font-size: 14px; margin-bottom: 8px">{{ item.name }}</div>
                              <div style="color: #a6a8b4; font-size: 10px">{{ item.desc ? item.desc : "---" }}</div>
                            </div>
                          </div>
                          <div style="margin-left: 10px">
                            <a-switch default-checked v-model="item.isHide" @change="hideChange(item)">
                              <a-icon slot="checkedChildren" type="check" />
                              <a-icon slot="unCheckedChildren" type="close" />
                            </a-switch>
                          </div>
                        </div>
                      </div>
                      <div v-else>
                        <a-empty style="margin-top: 80px" />
                      </div>
                    </div>
                  </a-modal>
                </div>

                <div v-else>
                  <a-empty style="margin-top: 100px" />
                </div>
              </a-layout-content>
            </a-layout>
          </a-tab-pane>
          <a-tab-pane key="3" tab="扫码入职设置">
            <a-spin :spinning="loadingcode" :delay="300">
              <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
                <a-form-item class="baseInfo-item" label>
                  <div class="processBox">
                    <div class="processBoxLCJS">流程介绍</div>
                    <div class="maBottom4">1.配置入职登记二维码并分享</div>
                    <div class="maBottom4">2.员工填写并提交入职登记信息</div>
                    <div>3.公司管理员在待入职管理中，完善员工信息并确认入职</div>
                  </div>
                </a-form-item>
                <a-form-item class="baseInfo-item" label="二维码有效期">
                  <div style="width: 200px; display: flex; align-items: center; font-size: 12px">
                    <a-input-number :min="1" v-model="timeDay" style="width: 100%; margin-right: 10px" @change="setAllContent" />
                    <div style="font-weight: 800; font-size: 14px">天</div>
                  </div>
                  <div v-if="timeDay">有效期：{{ FailureTime }}</div>
                </a-form-item>
                <a-form-item v-if="!isJF" class="baseInfo-item" label="工作性质">
                  <a-select
                    style="width: 200px"
                    v-decorator="[
                      'postType',
                      {
                        rules: [{ required: true, message: '请选择工作性质' }]
                      }
                    ]"
                    placeholder="请选择工作性质"
                    @change="postTypeSaoMaChange"
                    :default-value="SMDefault"
                    v-model="SMDefault"
                  >
                    <a-select-option v-for="item in postTypeOptions" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item class="baseInfo-item" label="渠道来源">
                  <a-select
                    v-model="channelDefault"
                    v-decorator="['postType', { rules: [] }]"
                    :default-value="channelDefault"
                    show-search
                    placeholder="请选择渠道来源"
                    style="width: 200px"
                    @change="channelSaoMaChange"
                  >
                    <a-select-option
                      v-for="(item, index) in siteChannelList"
                      :key="`${item.value}_${index}`"
                      :value="`${item.value}_${item.label}`"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
                <a-form-item v-if="typeValue === 1 && SMMubanList.length > 0" class="baseInfo-item" label="审批模板">
                  <a-select
                    style="width: 200px"
                    v-decorator="[
                      'postType',
                      {
                        rules: [{ required: true, message: '请选择审批模板' }]
                      }
                    ]"
                    placeholder="请选择审批模板"
                    @change="mubanSelect"
                    :default-value="muban"
                    v-model="muban"
                  >
                    <a-select-option v-for="item in SMMubanList" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item class="baseInfo-item" label="生成二维码">
                  <div style="width: 100%; display: flex; align-items: center; margin-top: 15px">
                    <img :src="codeimg" style="width: 150px; height: 150px" />
                    <div
                      style="position: absolute; z-index: 100; width: 150px; height: 150px; background-color: #252525aa"
                      v-if="refreshCode"
                      @click="creatCode"
                    >
                      <div
                        style="
                          cursor: pointer;
                          width: 100%;
                          height: 100%;
                          display: flex;
                          flex-flow: column;
                          align-items: center;
                          justify-content: center;
                        "
                      >
                        <a-icon type="reload" :style="{ fontSize: '18px', color: '#fff' }" />
                        <span style="color: #ffffff">刷新二维码</span>
                      </div>
                    </div>
                  </div>
                  <div>
                    <xq-icon type="icon-weiwancheng3x" class="primary_color weiwancheng3xCol" />
                    <div class="weiwancheng3xShow">{{ isJF ? "" : "工作性质、" }}渠道来源配置完成后，将成为二维码自带属性，请谨慎分享</div>
                  </div>
                  <div style="margin-top: 20px">
                    <a-button type="primary" @click="downloadCod" :disabled="refreshCode">下载二维码</a-button>
                  </div>
                </a-form-item>
              </a-form>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-spin>
  </div>
</template>

<script>
import { creatCode, loadAllChannelForSiteReq } from "@/api/staff/staff";
import { getSubjectListReq, editSubjectList, getCalendar, editType } from "./api";
import moment from "moment";
import { afterTime } from "@/utils/index";
import { getModelList_isUse } from "@/api/billing/billing";
import { mapGetters, mapState } from "vuex";
export default {
  data() {
    return {
      appItem: null,
      muban: undefined,
      SMDefault: 5,
      channelDefault: undefined,
      FailureTime: "",
      codeimg: "",
      loadingcode: false,
      refreshCode: false,
      timeDay: 7,
      typeValue: 1,
      appCode: null,
      siteId: null,
      loading: false,
      visible: false,
      dynamicDate: moment(moment().format("YYYY-MM"), "YYYY-MM"),
      weekList: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
      dateList: [],
      appList: [],
      companyId: this.$store.state.hr.companyId,
      subjectId: this.$route.query.id,
      isZXR: !window.location.host.includes("csxr.cn"),
      subjectList: [],
      setList: [],
      setName: "",
      appName: null,
      setCode: null,
      keyDate: 0,
      SMMubanList: [],
      siteChannelList: []
    };
  },
  computed: {
    ...mapState(["settings"]),
    ...mapGetters(["isJF"]),
    xcxCode() {
      if (window.location.host.includes("csxr.cn")) {
        return "csxr_xcx";
      }
      return this.settings.xcxCode;
    },
    postTypeOptions() {
      return this.$store.state.enums.postTypeLst.map((item) => ({
        value: item.value,
        label: item.title
      }));
    }
  },
  created() {
    if (localStorage.getItem("siteId")) {
      this.siteId = localStorage.getItem("siteId");
    }
    this.getSubjectList();
    // this.getCalendarList();
    // 请求二维码审核模板
    getModelList_isUse(this.companyId, "OnJob").then((res) => {
      this.SMMubanList = [];
      for (var i = 0; i < res.data.length; i++) {
        this.SMMubanList.push({
          value: res.data[i].id,
          label: res.data[i].typeName
        });
      }
      if (this.SMMubanList.length > 0) {
        // 默认选中第一条
        this.muban = this.SMMubanList[0].value;
        console.log(this.muban);
      } else {
        this.muban = undefined;
      }
    });
    this.loadSiteChannelList();
  },
  methods: {
    loadSiteChannelList() {
      loadAllChannelForSiteReq()
        .then((res) => {
          if (res.code === 200) {
            this.siteChannelList = res.data ? res.data.map((item) => ({ label: item.name, value: item.id })) : [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleOk(e) {
      this.visible = false;
    },
    handleCancel(e) {
      this.visible = false;
    },
    openSet(e) {
      this.setCode = e.code;
      this.setName = e.name;
      const appList = JSON.parse(JSON.stringify(this.appList));
      appList.forEach((item, index) => {
        if (item.code === this.setCode) {
          this.setList = JSON.parse(JSON.stringify(item.childList));
        }
      });
      this.visible = true;
    },
    menuChange(e) {
      this.appItem = e;
      this.appCode = e.code;
      this.appName = e.name;
      const subjectList = JSON.parse(JSON.stringify(this.subjectList));
      subjectList.forEach((item, index) => {
        if (item.code === this.appCode) {
          this.appList = JSON.parse(JSON.stringify(item.childList));
        }
      });
      this.keyDate += 1;
    },
    creatCode() {
      this.loadingcode = true;
      const par = {
        companyId: this.$route.query.id,
        status: this.typeValue,
        validDays: this.timeDay,
        postType: this.SMDefault,
        channelId: this.channelDefault ? this.channelDefault.split("_")[0] : "",
        expireDate: this.timeDay ? new Date(this.FailureTime + ":00").getTime() : ""
      };
      if (this.typeValue === 1) {
        // 待入职
        par.flowId = this.muban;
        if (!par.flowId && this.SMMubanList.length > 0) {
          this.$notification["success"]({
            message: "success",
            description: "请选择审批模板"
          });
          return;
        }
      }

      creatCode(par)
        .then((res) => {
          this.loadingcode = false;
          if (res.data) {
            this.typeValue = res.data.status;
            this.codeimg = res.data.qrCodeUrl;
            this.timeDay = res.data.validDays;
            this.SMDefault = res.data.postType;
            const date = new Date(res.data.expireDate); // 时间戳转date
            this.FailureTime = this.moment(date).format("YYYY-MM-DD HH:MM");
            if (res.data.flowId === null) {
              this.muban = undefined;
            } else {
              this.muban = res.data.flowId;
            }

            this.refreshCode = false;
            if (!this.codeimg) {
              this.refreshCode = true;
            }
          } else {
            this.loadingcode = false;
            this.$notification["success"]({
              message: "success",
              description: "二维码创建失败"
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.loadingcode = false;
        });
    },
    downloadCod() {
      window.open(this.codeimg + `?token=${this.$store.state.auth.token}`);
    },
    postTypeSaoMaChange(value) {
      this.SMDefault = value;
      this.refreshCode = true;
    },
    channelSaoMaChange(value) {
      this.channelDefault = value;
      this.refreshCode = true;
    },
    setAllContent(val) {
      this.timeDay = val;
      if (val) {
        var d = new Date();
        const newTime = afterTime(this.moment(d, "YYYY-MM-DD"), this.timeDay);
        this.FailureTime = newTime + " " + d.getHours() + ":" + d.getMinutes();
      }
      this.refreshCode = true;
    },
    onTypeChange(e) {
      this.typeValue = e.target.value;
      console.log(this.typeValue);
      this.refreshCode = true;
    },
    mubanSelect(value) {
      this.muban = value;
      this.refreshCode = true;
    },
    dateChange(e) {
      if (e === 1) {
        this.dynamicDate = moment(this.dynamicDate).subtract(1, "months");
        this.getCalendarList();
      }
      if (e === 2) {
        this.dynamicDate = moment(this.dynamicDate).subtract(-1, "months");
        this.getCalendarList();
      }
    },
    // 更改休假上班
    editTypeChange(item) {
      editType({
        date: item.date,
        dateType: item.dateType === 1 ? 2 : 1,
        siteId: this.siteId,
        subjectId: this.subjectId
      })
        .then((res) => {
          this.$message.success("切换成功");
          this.getCalendarList();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    mouseover(item, index) {
      this.$set(this.dateList, index, {
        ...this.dateList[index],
        hover: true
      });
    },
    mouseleave(item, index) {
      this.$set(this.dateList, index, {
        ...this.dateList[index],
        hover: false
      });
    },
    mouseover2(item, index) {
      this.$set(this.dateList, index, {
        ...this.dateList[index],
        hover2: true
      });
    },
    mouseleave2(item, index) {
      this.$set(this.dateList, index, {
        ...this.dateList[index],
        hover2: false
      });
    },
    // 返回今天
    goBack() {
      this.dynamicDate = moment(moment().format("YYYY-MM"), "YYYY-MM");
      this.getCalendarList();
    },
    // 选择月份变化
    onMonthChange() {
      this.getCalendarList();
    },
    // 查询的
    getCalendarList() {
      this.loading = true;
      getCalendar({
        month: moment(this.dynamicDate).format("MM"),
        year: moment(this.dynamicDate).format("YYYY"),
        siteId: this.siteId,
        subjectId: this.subjectId,
        "orders[0].desc": false,
        "orders[0].property": "date",
        subjectType: "company"
      })
        .then((res) => {
          this.loading = false;
          this.dateList = res.data;
          this.dateList = JSON.parse(JSON.stringify(res.data));
          if (moment(this.dateList[0].date).day() !== 1) {
            const num = moment(this.dateList[0].date).day() - 1;
            for (var i = 0; i < num; i++) {
              this.dateList.unshift({});
            }
          }

          if (moment(this.dateList[this.dateList.length - 1].date).day() !== 0) {
            const num = 7 - moment(this.dateList[this.dateList.length - 1].date).day();
            for (var o = 0; o < num; o++) {
              this.dateList.push({});
            }
          }
          this.dateList.forEach((item, index) => {
            if (item.initDateType === 1 && item.month === parseInt(moment(this.dynamicDate).format("MM"))) {
              item.style = "background:#24CDAA";
            }
            if (item.initDateType === 1 && item.month !== parseInt(moment(this.dynamicDate).format("MM"))) {
              item.style = "background:#24CDAA; opacity: 0.5;";
            }
            if (item.initDateType === 2 && item.month === parseInt(moment(this.dynamicDate).format("MM"))) {
              item.style = "background:#C0C0C0";
            }
            if (item.initDateType === 2 && item.month !== parseInt(moment(this.dynamicDate).format("MM"))) {
              item.style = "background:#C0C0C0; opacity: 0.5;";
            }
            if (item.initDateType === 3 && item.month === parseInt(moment(this.dynamicDate).format("MM"))) {
              item.style = "background:#FFA600";
            }
            if (item.initDateType === 3 && item.month !== parseInt(moment(this.dynamicDate).format("MM"))) {
              item.style = "background:#FFA600; opacity: 0.5;";
            }
          });
          this.dateList.forEach((item, index) => {
            item.hover = false;
          });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.loading = false;
        });
    },
    hideChange(e) {
      console.log(e);

      const arr = JSON.parse(JSON.stringify(e));
      this.loading = true;
      editSubjectList({
        id: arr.id,
        isHide: arr.isHide,
        subjectId: this.subjectId,
        subjectType: "company"
      })
        .then((res) => {
          console.log(res);
          this.$message.success("修改成功");
          this.getSubjectList();
        })
        .catch((error) => {
          this.getSubjectList();
          console.log("Error", error);
        });
    },
    getSubjectList() {
      getSubjectListReq({
        subjectId: this.subjectId,
        subjectType: "company",
        code: this.xcxCode
      })
        .then((res) => {
          this.loading = false;
          this.subjectList = JSON.parse(JSON.stringify(res.data));
          this.editIcon(this.subjectList);
          if (!this.appCode) {
            this.appCode = this.subjectList[0].code;
            this.appName = this.subjectList[0].name;
            this.appItem = this.subjectList[0];
          }
          if (this.appCode) {
            this.subjectList.forEach((item, index) => {
              if (item.code === this.appCode) {
                this.appList = JSON.parse(JSON.stringify(item.childList));
              }
            });
          }
          if (this.setCode) {
            this.appList.forEach((item, index) => {
              if (item.code === this.setCode) {
                this.setList = JSON.parse(JSON.stringify(item.childList));
              }
            });
          }
        })
        .catch((error) => {
          this.loading = false;
          console.log("Error", error);
        });
    },
    editIcon(data) {
      data.forEach((item, index) => {
        item.icon = item.icon.split(",");
        if (item.childList && item.childList.length) {
          this.editIcon(item.childList);
        }
      });
    },
    callback(key) {
      this.loadingcode = false;
      this.tabKey = key;
      if (this.tabKey === "3") {
        this.loadingcode = true;
        const d = new Date();
        const newTime = afterTime(this.moment(d, "YYYY-MM-DD"), this.timeDay);
        this.FailureTime = newTime + " " + d.getHours() + ":" + d.getMinutes();
        this.creatCode();
        //   getCode({
        //     companyId: this.$store.state.hr.companyId
        //   }).then(res => {
        //     this.loadingcode = false;
        //     if (res.data) {
        //       this.typeValue = res.data.status;
        //       this.codeimg = res.data.qrCodeUrl;
        //       this.timeDay = res.data.validDays;
        //       this.SMDefault = res.data.postType;
        //       const date = new Date(res.data.expireDate); // 时间戳转date
        //       this.FailureTime = this.moment(date).format("YYYY-MM-DD HH:MM");
        //       if (res.data.flowId === null) {
        //         this.muban = undefined;
        //       } else {
        //         this.muban = res.data.flowId;
        //         let has = false;
        //         for (var m = 0; m < this.SMMubanList.length; m++) {
        //           if (this.muban === this.SMMubanList[m].value) {
        //             has = true;
        //             break;
        //           }
        //         }
        //         if (!has) {
        //           this.muban = undefined;
        //         }
        //       }
        //     } else {
        //       var d = new Date();
        //       const newTime = afterTime(this.moment(d, "YYYY-MM-DD"), this.timeDay);
        //       this.FailureTime = newTime + " " + d.getHours() + ":" + d.getMinutes();
        //       this.refreshCode = true;
        //     }
        //   });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.processBox {
  background: #faf9f9;
  border-radius: 4px;
  padding: 14px 18px;
  color: #595959;
  font-size: 12px;
  div {
    line-height: 20px;
  }
  .processBoxLCJS {
    color: #3c3d43;
    font-size: 14px;
    margin-bottom: 12px;
  }
  .maBottom4 {
    margin-bottom: 4px;
  }
}
.weiwancheng3xCol {
  width: 14px;
  height: 14px;
  display: inline-block;
}
.weiwancheng3xShow {
  color: #7b7b7b;
  font-size: 12px;
  display: inline-block;
  width: 80%;
  vertical-align: text-top;
  line-height: 22px;
  margin-left: 10px;
}
.Set {
  font-size: 10px;
  color: var(--primary);
}
.iconStyle {
  color: var(--primary);
}
.editHoverStyle:hover {
  background: var(--primary10);
  color: var(--primary);
}
.contentBox {
  padding: 24px;
}
.datebox:hover {
  z-index: 1;
  transform: scale(1.2); // 放大1.2倍
  transition: all 0.3s; // 设置加载时间
  box-shadow: 0px 4px 12px 0px rgba(106, 102, 246, 0.2);
}
.now {
  border-radius: 50%;
  width: 32px;
  height: 32px;
  background: var(--primary);
  line-height: 32px;
  text-align: center;
  color: #fff;
}
.machine-status-menu {
  cursor: pointer;
  position: absolute;
  top: 24px;
  right: 5px;
  background: #fff;
  width: 80px;
  border-radius: 4px;
  // border: 1px solid #d9d9d9;
  box-shadow: 0px 0px 4px #e0e0e0;
  font-size: 10px;
  .editHoverStyle {
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.itemBox {
  display: flex;
  flex-wrap: wrap;
  // overflow: hidden;
  .item {
    width: 30%;
    height: 86px;
    background: #f4f6fa;
    margin-right: 18px;
    margin-bottom: 12px;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 16px;
    padding-right: 25px;
  }
  .item2 {
    width: 100%;
    height: 86px;
    background: #f4f6fa;
    margin-right: 18px;
    margin-bottom: 12px;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 16px;
    padding-right: 25px;
  }
}
.baseInfo-item {
  display: flex;
  flex-flow: row;
  // align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
</style>
